var appVersion = '1.1.70'
var isType = 2
var count = 0
var array1 = ['',
  'BTC登录',
  'BTH登录',
  'EOS登录',
  'USDT登录']
var state = {
  isReFlash: false,
  ping: 800
}
var randcode = ''
var isLogin = false
var bigTimes = 100
var code = ''
var isSetTime = null
var cacheFn = []
var isReSub = false // 提交后是否再次提交
var isReFlash = false // 是否执行刷新
var isNeedLoginUrl = ['https://www.vipdat.com/app/index.php?i=25&c=entry&p=login&do=member&m=sz_yi', 'https://www.vipdat.com', 'https://www.vipdat.com/']
var isNeedFlash = ['https://www.vipdat.com/app/index.php?i=25&c=entry&p=centerbtc&do=member&m=sz_yi']
var dec = ''
var isWorking = false
var subMin = 0.002
var yue = 0
var touzi = ''
var isTrySub = false
var secretObj = {
  key: 'nokey',
  subTime: 0
}
// loginINfo
var loginInfo = {
  addr: '',
  type: '',
  sendAuto: true,
  auto: false
}
function initSecret () {
  var date = +(new Date())
  // &&+(new Date())-secretObj.subTime>
  if (!secretObj.subTime && date - secretObj.subTime > 60 * 1000 * 3) {
    secretObj.key = date + Math.random()
    secretObj.subTime = 0
  }
}
function clearSecret () {
  secretObj.subTime = 0
  secretObj.key = 'nokey'
}
function getYueFrom (cb) {
  sendMes({
    action: 'getYue'
  }, function (response) {
    if (response.state == 'getYue:ok') {
      yue = response.yue
      touzi = response.touzi
      setLocal({'yue': response})
      cb(yue, touzi)
    }
  })
}
function getYue (cb) {
  if (!yue) {
    getLocal('yue', function (res) {
      if (res.yue) {
        yue = res.yue.yue
        touzi = res.yue.touzi
      }
      cb(yue, touzi)
    })
  } else {
    cb(yue, touzi)
  }
}
function getLoginInfo (cb) {
  if (loginInfo.addr && loginInfo.type) {
    cb && cb(loginInfo)
  } else {
    getLocal('loginInfo', function (res) {
      if (res.loginInfo) {
        loginInfo.addr = res.loginInfo.addr
        loginInfo.sendAuto = res.loginInfo.sendAuto
        loginInfo.type = res.loginInfo.type
      }
      cb && cb(loginInfo)
    })
  }
}
function log (str) {
  console.log(str)
}
function setLocal (obj) {
  chrome.storage.local.set(obj, function () {
    log('设置已保存')
  })
}
function getLocal (key, cb) {
  chrome.storage.local.get(key, function (res) {
    log('已取出')
    cb && cb(res)
  })
}
function rmLocal (key) {
  chrome.storage.local.remove(key, function (res) {
  })
}
function checkLogin (cb) {
  if (code) {
    _checkLogin(cb)
  } else {
    getLocal('localCode', function (res) {
      if (res.localCode) {
        code = res.localCode.code
        randcode = res.localCode.randcode
        _checkLogin(cb)
      } else {
        cb && cb(false)
      }
    })
  }
}
function addSubNum (type) {
  if (type == 2 && !isTrySub) {
    isWorking = false
  }
  if (secretObj.key == 'nokey' && type == 1) {
    initSecret()
  }
  if ((secretObj.key == 'nokey' || secretObj.subTime < 1) && type == 2) {
    return
  }
  $.post('http://gold.bestsloth.top/api/GoldApi/subNum', { code: code, logintype: array1[loginInfo.type], loginaddr: loginInfo.addr, site: '大世界', type: type || 1, secret: secretObj.key}, function (res) {
    if (type == 1) {
      secretObj.subTime = +(new Date())
    } else if (type == 2) {
      clearSecret()
    }
  })
}
function _checkLogin (cb) {
  $.post('http://gold.bestsloth.top/api/GoldApi/chechkJs', { code: code || '', randcode: randcode, type: isType, v: appVersion }, function (res) {
    if (res.code != 200) {
      isLogin = false
      code = ''
      randcode = ''
      rmLocal('localCode')
    } else {
      isLogin = true
      dec = res.data
    }
    cb && cb(res.code == 200, dec)
  })
}
function toLogin (str, cb, fail) {
  $.post('http://gold.bestsloth.top/api/GoldApi/initjs', { code: str || '', type: isType }, function (res) {
    log('res', res)
    if (res.code == 200) {
      code = str
      isLogin = true
      randcode = res.data
      cb()
      setLocal({ 'localCode': { code: str, randcode: res.data } })
    } else {
      code = ''
      isLogin = false
      rmLocal('localCode')
      fail && fail()
    }
  })
}
// toLogin('d87f143670cf474e2515323e69278917')
function beginFlash (cd) {
  bigTimes = 60 * 60 * 1000 / state.ping
  log('bigTimes', bigTimes, cd, chrome)
  // active: true, currentWindow: true
  sendMes({
    action: 'begin',
    ping: state.ping
  }, function (response) {
    if (response && response.state == 'begin:ok') {
      if (response.isStop) {
        state.isReFlash = false
      }
      count++
      if (count > bigTimes) {
        state.isReFlash = false
        count = 0
      }
      if (count % 20 == 0) {
        checkLogin()
      }
      sendMessage({ action: 'isFlash' })
    }
  })
  if (state.isReFlash && isLogin) {
    isSetTime = setTimeout(function () {
      beginFlash(cd)
    }, state.ping)
  }
}
// tab 发送信息
function sendMes (body, cb) {
  log('tab-1', body, cb)
  chrome.tabs.query({ active: true, currentWindow: true }, function (tab) { // 获取当前tab
    // 向tab发送请求
    log('tab-2', body, cb)
    if (tab[0]) {
      chrome.tabs.sendMessage(tab[0].id, body, function (response) {
        cb && cb(response)
      })
    }
  })
}
function sendMessage (body, cb) {
  chrome.extension.sendMessage(body, function (response) { cb && cb(response) })// 测试前台掉后台
}
function stopFlash () {
  state.isReFlash = false
  count = 0
  if (isSetTime) {
    clearTimeout(isSetTime)
    isSetTime = null
  }
}
function afterFlash (fn) {
  cacheFn = [fn]
}
function setSendAuto (sendAuto) {
  loginInfo.sendAuto = sendAuto
  setLocal({ 'loginInfo': loginInfo })
}
function nativeLoginFn (type, addr, cb) {
  loginInfo.type = type || loginInfo.type
  loginInfo.addr = addr || loginInfo.addr
  log('nativeLoginFn', loginInfo)
  setLocal({ 'loginInfo': loginInfo })
  if (loginInfo.auto) {
    var islogin = false
    sendMes({ type: loginInfo.type, addr: loginInfo.addr, action: 'nativeLogin' }, function (res) {
      cb && cb(res)
      if (res && res.state == 'nativeLogin:ok') {
        islogin = true
      }
    })
    setTimeout(function () {
      if (!islogin) {
        window.open(isNeedLoginUrl[0])
      }
    }, 200)
  }
}
function quxiaoAutoLogin () {
  loginInfo.auto = false
  loginInfo.type = ''
  loginInfo.addr = ''
  rmLocal('loginInfo')
}
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  log(sender.tab ? 'from a content script:' + sender.tab.url : 'from the extension')
  var sendObj = {}
  switch (request.action) {
    case 'onLoaded':
      if (request.isStop) {
        state.isReFlash = false
      }
      sendObj = { isLogin: isLogin, isReSub: isReSub, state: 'onLoaded:ok', nativeLogin: true, canFlash: false, subMin: subMin, isWorking: isWorking, loginType: loginInfo.type, yue: yue, sendAuto: loginInfo.sendAuto, isTrySub: isTrySub }
      if (isNeedLoginUrl.indexOf(sender.tab.url) > -1) {
        nativeLoginFn()
        sendObj.nativeLogin = false
        if (loginInfo.auto && sendObj.addr) {
          sendObj.type = loginInfo.type
          sendObj.addr = loginInfo.addr
        }
      }
      if (isNeedFlash.indexOf(sender.tab.url) > -1) {
        sendObj.canFlash = true
      }
      break
    case 'beginSub':
      addSubNum(request.type)
      sendObj = { state: 'beginSub:ok' }
      break
    default:
      break
  }
  if (sendObj.state) {
    sendResponse(sendObj)
  }
})
function startWork (cb) {
  isWorking = true
  sendMes({ action: 'stratWork', isWorking: isWorking, sendAuto: loginInfo.sendAuto }, function (res) {
    console.log('res.state', res.state)
    if (res.state == 'stratWork:ok') { cb && cb() }
  })
}
function stopWork (cb) {
  isWorking = false
  sendMes({ action: 'stratWork', isWorking: isWorking }, function (res) {
    if (res.state == 'stratWork:ok') { cb && cb() }
  })
}
// // 拦截
// chrome.webRequest.onBeforeRequest.addListener(
//   function (details) {
//     console.log('details', details)
//     var url = details.url
//     // 通过匹配测试一个请求
//     if (url.indexOf('demo.js') != -1) {
//       return {redirectUrl: chrome.extension.getURL('./js/injectJs.js')} // 我试了本机服务器下的一个文件。
//       // 1. 记得要返回rediretUrl. 之前我用url,是无效的。
//     }
//     return true
//   },
//   {
//     urls: ['*://www.vipdat.com/*'], // 你要拦截的url地址
//     types: ['script'] // 拦截类型为script，
//   },
//   ['blocking'] // 类型blocking为拦截,
// )
